package com.company.clientscard.shared.proxyManager;

import java.util.List;

import com.company.clientscard.shared.proxy.UserProxy;
import com.company.clientscard.shared.requestfactory.UsersRequestFactory;
import com.company.clientscard.shared.requestfactory.UsersRequestFactory.UsersRequestContext;
import com.google.gwt.core.client.GWT;
import com.google.gwt.view.client.HasData;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class UserProxyManager implements ProxyManager<UserProxy> {

	private UsersRequestContext context;

	public void refreshDisplays(HasData<UserProxy> display) {
		display.setVisibleRangeAndClearData(display.getVisibleRange(), true);
	}

	public void initContext() {
		UsersRequestFactory factory = GWT.create(UsersRequestFactory.class);
		factory.initialize(new SimpleEventBus());
		context = factory.context();
	}

	@Override
	public void add(UserProxy object, final HasData<UserProxy> display) {
		// TODO Auto-generated method stub
		context.save(object).fire(new Receiver<Void>() {

			@Override
			public void onSuccess(Void response) {
				// TODO Auto-generated method stub
				refreshDisplays(display);
			}
		});
	}

	@Override
	public void update(UserProxy object, final HasData<UserProxy> display) {
		context.update(object).fire(new Receiver<UserProxy>() {

			@Override
			public void onSuccess(UserProxy response) {
				refreshDisplays(display);
			}
		});

	}

	@Override
	public void setObjectList(final int firstRow, int numberOfRows,
			final HasData<UserProxy> display) {
		initContext();
		context.findAll(firstRow, numberOfRows).with("client")
				.fire(new Receiver<List<UserProxy>>() {

					@Override
					public void onSuccess(List<UserProxy> response) {
						// TODO Auto-generated method stub
						display.setRowData(firstRow, response);

					}
				});

	}

	@Override
	public UserProxy getProxyObject() {
		initContext();
		UserProxy object = context.create(UserProxy.class);
		return object;
	}

	@Override
	public UserProxy getProxyObject(UserProxy object) {
		initContext();
		UserProxy editibleObject = context.edit(object);
		return editibleObject;
	}

}
